package org.vectrics.recruiter.struts.tag;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.ecs.html.A;
import org.apache.log4j.Category;
import org.vectrics.SystemException;
import org.vectrics.common.html.BorderTable;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.html.TextHelper;
import org.vectrics.company.CompanyPersonCriteria;
import org.vectrics.employee.Employee;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.location.Location;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.user.RecruitPersonSearchCriteria;
import org.vectrics.recruiter.user.RecruitPersonSearcher;
import org.vectrics.security.Activity;
import org.vectrics.user.Person;
import org.vectrics.user.PersonSearchCriteria;
import org.vectrics.user.PersonSearcher;

public class RecruitUserManagerTag extends org.vectrics.user.web.struts.UserGroupManagerTag {

    private static final long serialVersionUID = -362854404797791898L;

    private static Category log = Category.getInstance(RecruitUserManagerTag.class);
    
    private Activity activity;
    
    private String permissionEmployeeView;
    
    private String permissionCandidateView;

    private String usertype = "all";

    public static String ALL_USERS = "all";

    public static String CANDIDATE = "candidate";

    public static String EMPLOYEE = "employee";

    public static String NO_ELEMENTS_MESSAGE = "No Data Found";

    private boolean showHomeCity = true;

    private boolean showEmail = true;

    private boolean showUserName = true;

    private boolean showCareerRole = false;

    private boolean showOfficeLocation = false;

    public RecruitUserManagerTag() {
        super();
        setWidth("90%");
    }

    @Override
    public boolean showNewUserLink() {
        return true;
    }

    @Override
    protected String getNoElementsMessage() {
        return NO_ELEMENTS_MESSAGE;
    }

    @Override
    protected PersonSearcher getPersonSearcher() {
        PersonSearcher searcher = null;

        if (usertype.startsWith(CANDIDATE)) {
            searcher = new RecruitPersonSearcher();
        } else {
            searcher = new PersonSearcher();
        }
        return searcher;
    }

    @Override
    protected PersonSearchCriteria getUserCriteria() {
        PersonSearchCriteria criteria = null;

        if (usertype.startsWith(ALL_USERS)) {
            log.debug("All roles requested, clearing roles");
            criteria = new PersonSearchCriteria();
        } else if (usertype.startsWith(CANDIDATE)) {
            showHomeCity = true;

            log.debug("Person will be considered a candidate if they have a candidateInfo record");
            criteria = new RecruitPersonSearchCriteria();
            ((RecruitPersonSearchCriteria) criteria).setCandidatesOnly(true);
            criteria.setNotEmployees(true);
        } else if (usertype.startsWith(EMPLOYEE)) {
            log.debug("getUserPrivileges() - using employee roles");
            criteria = new PersonSearchCriteria();
            criteria.setEmployeesOnly(true);

            showCareerRole = true;
            showHomeCity = false;
            showEmail = true;
            showUserName = true;
        } else {
            log.error("getUserPrivileges() - usertype not recognized: " + usertype);
            throw new SystemException("getUserPrivileges() - usertype not recognized: " + usertype);

        }
        criteria.getDomains().clear();
        criteria.addDomain(ThreadProperties.getDomain());
        Collection childDomains = ThreadProperties.getDomain().retrieveChildrenInBranch();
        criteria.getDomains().addAll(childDomains);
        return criteria;
    }

    protected String getNewUserHref() {
        return getContextPath() + "/admin/person/edit.do?newUser=true";
    }

    @Override
    protected void setTableProperties(final BorderTable table) {
        log.debug("setTableProperties() - no action");
    }

    @Override
    public String getDescription() {
        return null;
    }

    @Override
    protected String getPageListLink() {
        String link = null;
        if (usertype.startsWith(CANDIDATE)) {
            link = getContextPath() + "/admin/candidate/index.do?userType=" + getUsertype();
        } else if (usertype.startsWith(ALL_USERS)) {
            link = getContextPath() + "/admin/user/index.do?userType=" + getUsertype();
        } else if (usertype.startsWith(EMPLOYEE)) {
            link = getContextPath() + "/admin/employee/index.do?userType=" + getUsertype();
        }
        return link;
    }

    @Override
    public void makeHeaderCells(final Row row) {
        log.debug("makeHeaderCells() called.");
        row.setDefaultBgImage(getContextPath() + "/site-graphics/tbl_hdr.gif");

        Cell cell = row.addCell();
        cell.addElement(TextHelper.getFont("tableHdrFont", "Last Name"));
        // cell.setClass("tableHdrBg");

        cell = row.addCell();
        cell.addElement(TextHelper.getFont("tableHdrFont", "First Name"));
        // cell.setClass("tableHdrBg");

        if (showUserName) {
            cell = row.addCell();
            cell.addElement(TextHelper.getFont("tableHdrFont", "User Name"));
            // cell.setClass("tableHdrBg");
        }

        if (showEmail) {
            cell = row.addCell();
            cell.addElement(TextHelper.getFont("tableHdrFont", "E-Mail"));
            // cell.setClass("tableHdrBg");
        }

        if (showHomeCity) {
            cell = row.addCell();
            cell.addElement(TextHelper.getFont("tableHdrFont", "Location"));
            // cell.setClass("tableHdrBg");
        }

        if (showCareerRole) {
            cell = row.addCell();
            cell.addElement(TextHelper.getFont("tableHdrFont", "Career Role"));
        }

        if (showOfficeLocation) {
            cell = row.addCell();
            cell.addElement(TextHelper.getFont("tableHdrFont", getPhrase("prompt.employee.office.location")));
        }
        if (this.getActivity() != null) {
			if (this.getActivity().equals(Activity.MANAGE_EMPLOYEE)) {
				this.setPermission(this.getPermissionEmployeeView());
			}
			if (this.getActivity().equals(Activity.MANAGE_CANDIDATE)) {
				this.setPermission(this.getPermissionCandidateView());
			}
        }
        if(this.hasPermission()) {
        	cell = row.addCell();
        	cell.addElement(TextHelper.getFont("tableHdrFont", "Options"));
        	// cell.setClass("tableHdrBg");
        }
    }

    @Override
    protected void makeObjectRow(final Row row, final Person person) {
        Cell cell = row.addCell();
        cell.addElement(TextHelper.getFont("subFont", person.getLastName()));

        cell = row.addCell();
        cell.addElement(TextHelper.getFont("subFont", person.getFirstName()));

        if (showUserName) {
            cell = row.addCell();
            if (person.getUser() != null) {
                cell.addElement(TextHelper.getFont("subFont", person.getUser().getUserName() + "&nbsp;"));
            } else {
                cell.addElement(TextHelper.getFont("subFont", "&nbsp;"));
            }
        }

        if (showEmail) {
            cell = row.addCell();
            String email = null;
            if (person.getContactInfo() != null) {
                if (person.getContactInfo().getEmail() != null) {
                    email = person.getContactInfo().getEmail();
                }
            }
            cell.addElement(TextHelper.getFont("subFont", email));
        }

        if (showHomeCity) {
            String homeCity = null;
            cell = row.addCell();
            if (person.getContactInfo() != null) {
                if (person.getContactInfo().getHomeAddress() != null
                        && person.getContactInfo().getHomeAddress().getLocation() != null) {
                    Location location = person.getContactInfo().getHomeAddress().getLocation();
                    homeCity = location.getName();
                    if (location.getParent() != null) {
                        homeCity += ", " + location.getParent().getName();
                    }
                }
            }
            cell.addElement(TextHelper.getFont("subFont", homeCity));
        }

        if (showCareerRole) {
            cell = row.addCell();

            String careerRole = null;

            CompanyPersonCriteria criteria = new CompanyPersonCriteria();

            Collection domains = CoreServiceLocator.getSystemService().findAllDomains();
            criteria.setDomains(domains);
            criteria.setPerson(person);
            List<Employee> companyPersonList = null;
            companyPersonList = CoreServiceLocator.getCompanyService().findCompanyPersons(criteria, 0, 50);

            Table table = new Table();
            cell.addElement(table);
            table.setWidth("100%");
            Iterator<Employee> companyPersonIter = companyPersonList.iterator();
            while (companyPersonIter.hasNext()) {
                Employee companyPerson = companyPersonIter.next();
                if (companyPerson.getFunction() != null) {
                    Row careerRoleRow = table.addRow();
                    careerRoleRow.setDefaultCellFontClass("subFont");
                    Cell careerRoleCell = careerRoleRow.addCell();
                    careerRoleCell.setWidth("100%");
                    careerRoleCell.addText(companyPerson.getFunction().getDescription());
                }
            }
            if (isShowOfficeLocation()) {
                // Agrego la office Location.
                cell = row.addCell();
                Table officeLocationTable = new Table();
                cell.addElement(officeLocationTable);
                officeLocationTable.setWidth("100%");
                for (Employee companyPerson : companyPersonList) {
                    Row officeLocationRow = officeLocationTable.addRow();
                    officeLocationRow.setDefaultCellFontClass("subFont");
                    Cell officeLocationCell = officeLocationRow.addCell();
                    if (companyPerson.getLocation() != null) {
                        officeLocationCell.addText(companyPerson.getLocation().getName());
                    } else {
                        officeLocationCell.addText("");
                    }
                }
            }

        }
        if (this.getActivity() != null) {
			if (this.getActivity().equals(Activity.MANAGE_EMPLOYEE)) {
				this.setPermission(this.getPermissionEmployeeView());
			}
			if (this.getActivity().equals(Activity.MANAGE_CANDIDATE)) {
				this.setPermission(this.getPermissionCandidateView());
			}
        }
        if(this.hasPermission()) {
        	cell = row.addCell();
        	A detailLink = new A();
        	detailLink.setHref(getContextPath() + "/admin/user/view.do?userId=" + person.getId());
        	detailLink.setClass("subLink");
        	detailLink
        		.setStyle("color:#A7D34B; font-weight:normal; text-decoration:none; font-family:arial,tahoma,verdana,sans-serif; font-size:11px; font-size-adjust:none; font-style:normal; font-variant:normal;");
        	detailLink.addElement(getPhrase("phrase.view"));
        	cell.addElement(detailLink);
        }
    }

    public String getUsertype() {
        return usertype;
    }

    public void setUsertype(final String userType) {
        log.debug("setUsertype() - usertype = " + usertype);
        usertype = userType;
    }

    /**
     * @return the showHomeCity
     */
    public boolean isShowHomeCity() {
        return showHomeCity;
    }

    /**
     * @param showHomeCity
     *            the showHomeCity to set
     */
    public void setShowHomeCity(final boolean showHomeCity) {
        this.showHomeCity = showHomeCity;
    }

    /**
     * @return the showEmail
     */
    public boolean isShowEmail() {
        return showEmail;
    }

    /**
     * @param showEmail
     *            the showEmail to set
     */
    public void setShowEmail(final boolean showEmail) {
        this.showEmail = showEmail;
    }

    /**
     * @return the showUserName
     */
    public boolean isShowUserName() {
        return showUserName;
    }

    /**
     * @param showUserName
     *            the showUserName to set
     */
    public void setShowUserName(final boolean showUserName) {
        this.showUserName = showUserName;
    }

    public boolean isShowCareerRole() {
        return showCareerRole;
    }

    public void setShowCareerRole(final boolean showCareerRole) {
        this.showCareerRole = showCareerRole;
    }

    /**
     * @return the showOfficeLocation
     */
    public boolean isShowOfficeLocation() {
        return showOfficeLocation;
    }

    /**
     * @param showOfficeLocation
     *            the showOfficeLocation to set
     */
    public void setShowOfficeLocation(final boolean showOfficeLocation) {
        this.showOfficeLocation = showOfficeLocation;
    }

	public static String getALL_USERS() {
		return ALL_USERS;
	}

	public static void setALL_USERS(String all_users) {
		ALL_USERS = all_users;
	}

	public void setPermissionEmployeeView(String permissionEmployeeView) {
		this.permissionEmployeeView = permissionEmployeeView;
	}

	public String getPermissionEmployeeView() {
		return permissionEmployeeView;
	}

	public void setPermissionCandidateView(String permissionCandidateView) {
		this.permissionCandidateView = permissionCandidateView;
	}

	public String getPermissionCandidateView() {
		return permissionCandidateView;
	}

	public void setActivity(Activity activity) {
		this.activity = activity;
	}

	public Activity getActivity() {
		return activity;
	}

}